package easycloud.ecs.web.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import easycloud.ecs.common.domain.User;
import easycloud.ecs.web.exception.DomainNotFoundException;
import easycloud.ecs.web.exception.SessionNotFoundException;
import easycloud.ecs.web.service.UserService;
import easycloud.ecs.web.util.SessionAttributes;

@Controller
public class BaseController {

	@Inject
	protected UserService userService;

	public User getUser(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(
				SessionAttributes.CUR_USER);
		if (user == null) {
			throw new SessionNotFoundException(User.class);
		}
		return user;
	}

	public User getUserWithSession(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(
				SessionAttributes.CUR_USER);
		if (user != null) {
			Integer id = user.getId();
			user = userService.getUser(id);
			if (user == null) {
				throw new DomainNotFoundException(User.class, id);
			}
		} else {
			throw new SessionNotFoundException(User.class);
		}
		return user;
	}

	public void refreshSession(HttpServletRequest request) {
		User user = getUserWithSession(request);
		HttpSession session = request.getSession();
		session.setAttribute(SessionAttributes.CUR_USER, user);
	}
}
